package com.xoa.controller.cas;

import com.xoa.controller.login.loginController;
import com.xoa.dao.casConfig.CasConfigMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.common.SyslogMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.qiyeWeixin.UserWeixinqyMapper;
import com.xoa.dao.sys.SysInterfaceMapper;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.dao.users.UserExtMapper;
import com.xoa.dao.users.UserFunctionMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.casContrast.dao.Oa2SsoMapper;
import com.xoa.model.casConfig.CasConfig;
import com.xoa.model.common.SysPara;
import com.xoa.model.common.Syslog;
import com.xoa.model.department.Department;
import com.xoa.model.qiyeWeixin.UserWeixinqy;
import com.xoa.model.sys.InterfaceModel;
import com.xoa.model.users.OrgManage;
import com.xoa.model.users.UserOnline;
import com.xoa.model.users.Users;
import com.xoa.service.casConfig.CasConfigService;
import com.xoa.service.sys.SysLogService;
import com.xoa.service.sys.SystemInfoService;
import com.xoa.service.sys.impl.SystemInfoServiceImpl;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ResponseWithHttpClient;
import com.xoa.util.ToJson;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.sso.CASEncrypt;
import com.xoa.util.sso.CASUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @创建作者:李然  Lr
* @方法描述：Cas
* @创建时间：16:55 2019/6/14
**/
@Controller
@RequestMapping("xoaCas")
public class CasController {

    @Resource
    private loginController loginController;

    @Resource
    private CasConfigService casConfigService;

    @Autowired
    private CasConfigMapper casConfigMapper;
    
    @Autowired
    private Oa2SsoMapper oa2SsoMapper;

    @Autowired
    UserFunctionMapper userFunctionMapper;

    @Autowired
    private SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    private SysLogService sysLogService;

    private String casHost =null;

    private static String lastOAtargeturl = "";

    //映射区
    @RequestMapping("newCas")
    public String newCas(){
        return "app/public/newCas";
    }

    @RequestMapping("interceptCas")
    public String intercept(){
        return "app/public/interceptCas";
    }


    //功能区
    /**
    * @创建作者:李然  Lr
    * @方法描述：保存cas配置信息
    * @创建时间：11:42 2019/6/20
    **/
    @RequestMapping("/saveCas")
    @ResponseBody
    public ToJson saveCas(HttpServletRequest request, CasConfig casConfig){
        return casConfigService.save(request,casConfig);
    }

    /**
    * @创建作者:李然  Lr
    * @方法描述：回显cas配置数据
    * @创建时间：16:22 2019/6/20
    **/
    @RequestMapping("/showCas")
    @ResponseBody
    public ToJson saveCas(HttpServletRequest request){
        return casConfigService.showCas(request);
    }


    /**
     * @创建作者:李然  Lr
     * @方法描述：跳转登陆方法，传入用户名和空密码
     * @创建时间：17:09 2019/6/14
     **/
    @RequestMapping("/login")
    @ResponseBody
    public void login(HttpServletRequest request,HttpServletResponse response,String OAtargeturl) throws Exception{

        Syslog sysLog = new Syslog();
        CasConfig casConfig= null;
        try {
            casConfig = casConfigMapper.selectOneCas();
        } catch (Exception e) {
            return ;
        }

        if(casConfig != null){
            String loginId=casConfig.getCasLoginOrg();
            //获取cas登录用户名
            casHost = casConfig.getCasAddress();
            //String gh=request.getRemoteUser();
            String gh=getTask(request,response);
            String username = oa2SsoMapper.selectAllByGH(gh);
            if(StringUtils.checkNull(username)){
                username = gh;
            }
            try {
                sysLog.setUserId(gh);
                sysLog.setTime(new Date());
                sysLog.setIp(IpAddr.getIpAddress(request));
                sysLog.setType(1);
                sysLog.setRemark(username);
                sysLog.setClientType(5);
                sysLog.setClientVersion(request.getParameter("clientVersion"));
                syslogMapper.save(sysLog);
            }finally {
                String OAtargeturl1 = "";

                if (OAtargeturl != null && OAtargeturl.contains("!")){
                    OAtargeturl = OAtargeturl.replace("!","&");
                }
                if (OAtargeturl == null) {
                    OAtargeturl = "";
                }

                if ("".equals(OAtargeturl)) {
                    if (!"".equals(lastOAtargeturl)) {
                        OAtargeturl1 = lastOAtargeturl;
                    } else {
                        OAtargeturl1 = "/main";
                    }
                } else {
                    OAtargeturl1 = OAtargeturl;
                    lastOAtargeturl = OAtargeturl;
                }


                if(username!=null&&!"".equals(username.trim())) {
                    //System.out.println("获取对照用户名" + username);
                    ssoLoginEnter(request, response, loginId, username,OAtargeturl1);
                    return;
                }
            }
        } else {
            String info = request.getParameter("info");
            if(StringUtils.checkNull(info)){
                info = request.getParameter("login_info");
            }
            //System.out.println("单点登录人员的密文为："+info);
            if(!StringUtils.checkNull(info)){
                String userInfoJson = CASEncrypt.decrypt(info, "dMBnHEHW");
                JSONObject ssoUser = JSONObject.fromObject(userInfoJson);
                if(ssoUser!=null){
                   // System.out.println("单点登录人员的警号为："+ssoUser.getString("policeno"));
                    //idcard  身份证号
                    Users idcard = usersMapper.getUserByIdNumber(ssoUser.getString("idcard"));
                    if(idcard == null){
                        return;
                    }
                    ssoLoginEnter(request, response, null, idcard.getByname(),"/main");
                }
            } else {
                String userName = request.getParameter("userName");
                if(!StringUtils.checkNull(userName)){
                    ssoLoginEnter(request, response, null, userName,"/main");
                }
            }
        }
        return ;
    }

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private OrgManageMapper orgManageMapper;
    @Autowired
    private UsersService usersService;
    @Autowired
    private SystemInfoService systemInfoService;
    @Autowired
    private SysParaMapper sysParaMapper;
    @Autowired
    private SyslogMapper syslogMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private UserWeixinqyMapper userWeixinqyMapper;
    private final String one = "1";
    /**
     * @创建作者:李然  Lr
     * @方法描述：公共获取用户名方法
     * @创建时间：17:09 2019/6/14
     **/
    public String getTask(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String tkt =request.getParameter("ticket");
        //当前的访问路径的协议及地址和端口号
        String service = request.getScheme()+"://"+request.getServerName();
        int port=request.getServerPort();
        if(port!=80&&port!=443){//默认端口，不加在跳转路径下
            service+=":"+request.getServerPort();
        }
        service+=request.getRequestURI();
        //判断票据是否为空，为空则未经过认证，需重新定向到认证，否者则认证成功
        if (tkt == null || tkt.length() == 0)
        {
            String redir = casHost +"/login?service=" + service;
            response.sendRedirect(redir);
            return null;
        }else {
            //校验ticket，获取用户信息
            String validateurl = casHost + "/serviceValidate?" +
                    "ticket=" + tkt + "&" +
                    "service=" + service;

            //发送请求
            String data =ResponseWithHttpClient.getResponseWithHttpClient(validateurl, "UTF-8");

            if(data != null) {
                String username = null;
                Pattern pt = Pattern.compile("<cas:user>(.*)</cas:user>");
                Matcher match = pt.matcher(data);
                while (match.find()) {
                    username=match.group(1);
                }
                if(username == null) {
                    return null;
                }
                return username;
            }
        }
        return null;
    }

    ToJson<Users> loginEnter( String username,
                             String password, String loginId, String userAgent, String locales,
                             HttpServletRequest request, HttpServletResponse response, Integer h5Login)
            throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min

        CookiesUtil.setCookie(response, "redisSessionId", request.getSession().getId());
        Cookie redisSessionCookie = new Cookie("redisSessionId", request.getSession().getId());
        //获取token值，安卓华为有值，其它客户端为空或null
        String pushToken = request.getParameter("pushToken");

        Users userAll = usersMapper.selectUserByUserId(username);
        if ("android".equals(userAgent.toLowerCase()) || "ios".equals(userAgent.toLowerCase())) {
            if (userAll!=null) {
                userAll.setIcqNo(pushToken == null ? "" : pushToken);
                usersMapper.updateIcqNo(userAll);
            }
        }
        if (StringUtils.checkNull(loginId)) {
            List<OrgManage> org = orgManageMapper.queryId();
            if (org != null && org.size() > 0) {
                loginId = org.get(0).getOid().toString().trim();
            }
        }
        // 获取企业微信和钉钉登陆判断参数
        String thirdPartyType = request.getParameter("thirdPartyType");

        ToJson<Users> json = new ToJson<Users>(0, null);
        //判断禁止登录用户是否可以登录
        if (!StringUtils.checkNull(username)) {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> m = systemInfoService.getSystemInfo(realPath, locale, request);
            int oaUserLimit = 0;

            ToJson exJson = loginController.examineRegister(request, m);
            if (!exJson.isFlag()) {
                return exJson;
            }

            if ("不限制".equals(m.get("oaUserLimit"))) {

            } else {
                //授权人数
                oaUserLimit = Integer.parseInt(m.get("oaUserLimit"));
            }
            SessionUtils.putSession(request.getSession(), "loginDateSouse", loginId, redisSessionCookie);
            //允许登录用户数
            int canLoginUser = usersMapper.getLoginUserCount();
            if (oaUserLimit != 0) {
                if (canLoginUser > oaUserLimit) {
                    json.setCode(LoginState.LOGINTIME);
                    json.setMsg("允许登录OA用户达到上限，请联系管理员！");
                    json.setFlag(1);
                    return json;
                }
            }
        }

        Cookie redisSessionCookie1 = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie1);
        //加入操作日志处理
        Syslog sysLog = new Syslog();
        sysLog.setUserId(users.getUserId() + "");
        sysLog.setType(10);
        sysLog.setTypeName("错误用户名");
        InetAddress currentIp = IpAddr.getCurrentIp();
        sysLog.setIp(currentIp.toString().substring(1, currentIp.toString().length()));
        sysLog.setRemark("");
        String userAgent1 = request.getParameter("userAgent");
        if ("iOS".equals(userAgent1)) {
            //添加客户端类型
            sysLog.setClientType(3);
            SysPara Version = sysParaMapper.querySysPara("APP_IOS_Version");
            sysLog.setClientVersion(Version.getParaValue());
        } else if ("android".equals(userAgent1)) {
            sysLog.setClientType(4);
            SysPara Version = sysParaMapper.querySysPara("APP_Android_Version");
            sysLog.setClientVersion(Version.getParaValue());
        } else if ("pc".equals(userAgent1)) {
            sysLog.setClientType(2);
            SysPara Version = sysParaMapper.querySysPara("APP_PC_Version");
            sysLog.setClientVersion(Version.getParaValue());
        } else {
            sysLog.setClientType(1);


            String clientVersion = request.getParameter("clientVersion");
            if (clientVersion != null && clientVersion.length() > 0) {
                sysLog.setClientVersion(clientVersion);
            } else {
                sysLog.setClientVersion(SystemInfoServiceImpl.softVersion);
            }
        }

        if (StringUtils.checkNull(username)) {
            json.setFlag(1);
            json.setCode(LoginState.LOGINPASSWORDERR);
            json.setMsg("用户名或用户不存在");
            return json;
        }
        ContextHolder.setConsumerType("xoa" + loginId);
        Users user = this.selectUserAllInfoByName(username, request, loginId, password, h5Login, thirdPartyType);

        if (user == null) {
            request.getSession().setAttribute("message", "errOne");
            json.setMsg("用户名或用户不存在");
            sysLog.setRemark("USER_NAME=" + username);
            sysLog.setTime(new Date(System.currentTimeMillis()));
            syslogMapper.save(sysLog);
            json.setCode(LoginState.LOGINPASSWORDERR);
            json.setFlag(1);
            return json;

        }
        json.setBirthday(user.getBirthday());
        List<SysPara> list = sysParaMapper.selectAll();
        String pd = "";
        String xts = "";
        String cz = "";
        for (SysPara sysPara : list) {
            if ("SEC_RETRY_BAN".equals(sysPara.getParaName())) {
                pd = sysPara.getParaValue();
            }
            if ("SEC_RETRY_TIMES".equals(sysPara.getParaName())) {
                xts = sysPara.getParaValue();
            }
            if ("SEC_BAN_TIME".equals(sysPara.getParaName())) {
                cz = sysPara.getParaValue();
            }
        }
        int qk = 1;
        json = loginController.login(json, qk, user, username, password, pd, cz, xts, request, loginId, locales);

        return json;

    }

    public Users selectUserAllInfoByName(String byname, HttpServletRequest req, String loginId, String userPassword, Integer h5Login,String thirdPartyType) {
        Users user = usersMapper.selectUserAllInfoByName(byname);
        if (user != null) {
            Boolean isPassWordRight = usersService.checkPassWordUser(user.getByname(), user.getPassword(), userPassword);
            //cas 不需要密码
            if (null != h5Login && h5Login == 1) {
                isPassWordRight = true;
            }
            // 判断是否是企业微信或者钉钉登陆 直接设置为true
            if(!StringUtils.checkNull(thirdPartyType)&&thirdPartyType.equals("1")){
                UserWeixinqy userWeixinqy = userWeixinqyMapper.selUserByUserId(user.getUserId());
                if(userWeixinqy!=null&&!StringUtils.checkNull(userWeixinqy.getOpenId())){
                    isPassWordRight = true;
                }
            }
            if (isPassWordRight) {
                user.setIsPassWordRight("ok");
            } else {
                user.setIsPassWordRight("err");
                return user;
            }
            //多组织公司名称 ，不能调用已经注释的，里面只有一个公司,读取公司名称时要切库切到1001，切换之后要切到选择的库

            /* UnitManage nitManage = unitManageMapper.showUnitManage();*/
            OrgManage orgManageById = null;
            if (!StringUtils.checkNull(loginId)) {
                ContextHolder.setConsumerType("xoa1001");
                orgManageById = orgManageMapper.getOrgManageById(Integer.valueOf(loginId));
            }
            //没有传的默认为1001
            else {
                ContextHolder.setConsumerType("xoaxoa1001");
                orgManageById = orgManageMapper.getOrgManageById(Integer.valueOf(1001));
            }
            user.setCompanyName(orgManageById.getName());
            //查询公司名称后要切回来
            ContextHolder.setConsumerType("xoa" + loginId);
            if (user.getDeptId() != null) {
                Department dep = departmentMapper.getDeptById(user.getDeptId());
                if (dep != null) {
                    user.setDeptName(dep.getDeptName());
                }
            }

            Syslog sysLog = new Syslog();
            sysLog.setLogId(0);
            sysLog.setUserId(user.getUserId());
            String ip = "";
            SysPara sysParaHost = sysParaMapper.querySysPara("IM_HOST");
            //根据商量先获取数据库IM_STUTES的字段是1则返回手动配置的IP地址 是0的情况下让手机端自己获取ip和端口,返回为空
            SysPara sysParaStutes = sysParaMapper.querySysPara("IM_STUTES");
            SysPara sysParaPort = sysParaMapper.querySysPara("IM_PORT");

            if (sysParaStutes != null && !StringUtils.checkNull(sysParaStutes.getParaValue()).booleanValue()) {
                if (one.equals(sysParaStutes.getParaValue())) {
                    user.setGimPort(sysParaPort.getParaValue());
                    user.setGimHost(sysParaHost.getParaValue());
                    user.setImRegisterIp(sysParaHost.getParaValue());
                } else {
                    user.setGimPort("");
                    user.setGimHost("");
                    user.setImRegisterIp("");
                }

            }
            sysLog.setTime(new Date());


            sysLog.setIp(IpAddr.getIpAddress(req));
            sysLog.setType(1);
            String userAgent = req.getParameter("userAgent");
            if ("iOS".equals(userAgent)) {
                sysLog.setRemark("iOS端");
                //添加客户端类型
                sysLog.setClientType(3);
                SysPara Version = sysParaMapper.querySysPara("APP_IOS_Version");
                sysLog.setClientVersion(Version.getParaValue());
            } else if ("android".equals(userAgent)) {
                sysLog.setRemark("安卓端");
                sysLog.setClientType(4);
                SysPara Version = sysParaMapper.querySysPara("APP_Android_Version");
                sysLog.setClientVersion(Version.getParaValue());
            } else if ("pc".equals(userAgent)) {
                sysLog.setRemark("PC端");
                sysLog.setClientType(2);
                SysPara Version = sysParaMapper.querySysPara("APP_PC_Version");
                sysLog.setClientVersion(Version.getParaValue());
            } else {
                sysLog.setRemark("网页端");
                sysLog.setClientType(1);
                String clientVersion = req.getParameter("clientVersion");
                if (clientVersion != null && clientVersion.length() > 0) {
                    sysLog.setClientVersion(clientVersion);
                } else {
                    sysLog.setClientVersion(SystemInfoServiceImpl.softVersion);
                }
            }
            //添加版本号
            /*String clientVersion =  req.getParameter("clientVersion");
            if(clientVersion!=null&& clientVersion.length()>0){
                sysLog.setClientVersion(clientVersion);
            }else{
                sysLog.setClientVersion(SystemInfoServiceImpl.softVersion);
            }*/
            StringBuffer url = req.getRequestURL();
            //syslogMapper.save(sysLog);
            //添加完字段的
            syslogMapper.save2(sysLog);

        }

        if (user!=null){
            user.setPassword("");
        }
        return user;
    }

   public boolean casLogin(HttpServletRequest request, HttpServletResponse response,CasConfig casConfig,String Url) throws Exception {
        if (casConfig != null) {
//            String loginId = casConfig.getCasLoginOrg();
//            Integer h5Login = 1;
//            String userAgent = "pcc";
//            String password = "temp";
//            String locales = null;
//            casHost = casConfig.getCasAddress();
//            //获取cas登录用户名
//            String username = getTask(request, response);
//            if (username != null && !username.trim().equals("")) {
//                ToJson toJson = this.loginEnter(username, password, loginId, userAgent, locales, request, response, h5Login);
//                if (toJson.isFlag()) {
//                    try {
//                        String serverName = request.getServerName();
//                        String service = request.getScheme() + "://" + serverName;
//                        int port = request.getServerPort();
//                        if (!"80".equals(port) && !"443".equals(port)) {//默认端口，不加在跳转路径下
//                            service += ":" + request.getServerPort();
//                        }
//                        service = service + Url;
//
//                        Users users = (Users) toJson.getObject();
//                        String company = "company";
//                        String deptId = "deptId";
//                        String language = "language";
//                        //放入Cokie
//                        CookiesUtil.setCookie(response, company, loginId);
//                        CookiesUtil.setCookie(response, deptId, String.valueOf(users.getDeptId()));
//                        CookiesUtil.setCookie(response, language, "zh_CN");
//                        CookiesUtil.setCookie(response, "sex",  users.getSex());
//                        CookiesUtil.setCookie(response, "uid", String.valueOf(users.getUid()));
//                        CookiesUtil.setCookie(response, "userId", users.getUserId());
//                        CookiesUtil.setCookie(response, "userName", users.getUserName());
//                        CookiesUtil.setCookie(response, "userId", users.getUserId());
//                        CookiesUtil.setCookie(response, "userPriv", String.valueOf(users.getUserPriv()));
//                        CookiesUtil.setCookie(response, "userPrivName", users.getUserPrivName());
//                        response.sendRedirect(service);
//                        return true;
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        return false;
//                    }
//                } else {
//                    return false;
//                }
//            } else {
                return false;
//            }
        } else {
            return false;
        }
    }


    public static Map<String,Object> userCountMap =new HashedMap();

    public ToJson<Users> ssoLoginEnter(HttpServletRequest request, HttpServletResponse response,String loginId,String username,String OAtargeturl) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min

        String serverName = request.getServerName();
        String targetUrl = request.getScheme() + "://" + serverName;
        int port = request.getServerPort();
        if (80!=port && 443!=port) {//默认端口，不加在跳转路径下
            targetUrl += ":" + request.getServerPort();
        }
        CASUtils casUtils = new CASUtils();
        HttpSession session = request.getSession();

        //OAtargeturl = StringUtils.checkNull(OAtargeturl) ? "/main":OAtargeturl;
        if(casUtils.isLogin(session)) {
            response.sendRedirect(targetUrl + OAtargeturl);
        }else {

            CookiesUtil.setCookie(response, "redisSessionId", request.getSession().getId());
            Cookie redisSessionCookie = new Cookie("redisSessionId", request.getSession().getId());
            if (StringUtils.checkNull(loginId)) {
                List<OrgManage> org = orgManageMapper.queryId();
                if (org != null && org.size() > 0) {
                    loginId = org.get(0).getOid().toString().trim();
                }
            }


            ToJson<Users> json = new ToJson<Users>(0, null);
            if (StringUtils.checkNull(username)) {
                json.setFlag(1);
                json.setCode(LoginState.LOGINPASSWORDERR);
                json.setMsg("用户名或用户不存在");
                return json;
            }
            ContextHolder.setConsumerType("xoa" + loginId);
            Users user = usersMapper.selectUserAllInfoByName(username);
            if (user == null) {
               /* request.getSession().setAttribute("message", "errOne");
                json.setMsg("用户名或用户不存在");
                json.setCode(LoginState.LOGINPASSWORDERR);
                json.setFlag(1);*/
                response.sendRedirect(targetUrl + "/defaultIndexErrCas");
                return json;

            }

            List<SysPara> list = sysParaMapper.selectAll();
            String pd = "";
            String xts = "";
            String cz = "";
            for (SysPara sysPara : list) {
                if ("SEC_RETRY_BAN".equals(sysPara.getParaName())) {
                    pd = sysPara.getParaValue();
                }
                if ("SEC_RETRY_TIMES".equals(sysPara.getParaName())) {
                    xts = sysPara.getParaValue();
                }
                if ("SEC_BAN_TIME".equals(sysPara.getParaName())) {
                    cz = sysPara.getParaValue();
                }
            }


            //获取当前用户的登录日志
            ToJson<Syslog> modifyPwdLog = sysLogService.getLoginLog(request);
            if (user.getLastVisitTime() != null) {
                user.setLastVisitTime(new Date());
                usersService.updateLoginTime(user);
            } else {
                //判断他的size小于等于1，因为在查用户user信息时写入log日志的，因此第一次登录size为1
                if (modifyPwdLog.getObj() == null || modifyPwdLog.getObj().size() <= 1) {
                    json.setCode("FirstLogin");
                } else {
                    user.setLastVisitTime(new Date());
                    usersService.updateLoginTime(user);
                }
            }

            if (StringUtils.checkNull(loginId)) {
                List<OrgManage> org = orgManageMapper.queryId();
                if (org != null && org.size() > 0) {
                    loginId = org.get(0).getOid().toString().trim();
                }
            }
            user.setCompanyId(loginId);
            //判断用户头像
            if (StringUtils.checkNull(user.getAvatar())) {
                if (!StringUtils.checkNull(user.getSex())) {
                    user.setAvatar(user.getSex());
                } else {
                    user.setAvatar("0");
                }

            } else {
                if (user.getAvatar().equals("0") || user.getAvatar().equals("1")) {
                    if (!StringUtils.checkNull(user.getSex())) {
                        user.setAvatar(user.getSex());
                    } else {
                        user.setAvatar("0");
                    }
                } else {
                    //判断用户头像是否找得到
                    String classpath = this.getClass().getResource("/").getPath();
                    String webappRoot = classpath.replaceAll("WEB-INF/classes/", "ui/img/user/");
                    File file_avtor = new File(webappRoot + user.getAvatar());
                    if (!file_avtor.exists()) {
                        user.setAvatar(user.getSex());
                    }
                }
            }
            json.setObject(user);
            json.setFlag(0);

            //通过userId查询用户是否存在于静态map中
            UserOnline userOnline = (UserOnline) userCountMap.get(user.getUserId());
            //如果不存在
            if (userOnline == null) {
                //声明一个新的用户在线数据
                UserOnline userOnlineInfo = new UserOnline();
                try {
                    String format = DateFormatUtils.formatDate(new Date());
                    Integer nowTime = DateFormatUtils.getNowDateTime(format);
                    userOnlineInfo.setClient((byte) 2);
                    userOnlineInfo.setPCtime(nowTime);
                    userOnlineInfo.setPCsid(request.getSession().getId());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {//如果存在
                if (!userOnline.getPCsid().equals("")) {
                    try {
                        String format = DateFormatUtils.formatDate(new Date());
                        Integer nowTime = DateFormatUtils.getNowDateTime(format);
                        userOnline.setPCtime(nowTime);
                        userCountMap.put(user.getUserId(), userOnline);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        String format = DateFormatUtils.formatDate(new Date());
                        Integer nowTime = DateFormatUtils.getNowDateTime(format);
                        userOnline.setPCtime(nowTime);
                        userOnline.setPCsid(request.getSession().getId());
                        userCountMap.put(user.getUserId(), userOnline);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("paraName", "IM_WINDOW_CAPTION");
            params.put("paraValue", user.getPara().getParaValue());
            params.put("loginDateSouse", loginId);//组织id
            params.put("LOCALE_SESSION_ATTRIBUTE_NAME", "zh_CN");//语言


            String functionIdStr = userFunctionMapper.getUserFuncIdStr(user.getUserId());
            params.put("functionIdStr", functionIdStr);

            List<InterfaceModel> interfaceModels = sysInterfaceMapper.getInterfaceInfo();
            if (0 == user.getTheme() || null == user.getTheme()) {
                user.setTheme((byte) Integer.parseInt(interfaceModels.get(0).getTheme()));
            }

            String theme = "theme" + user.getTheme();
            params.put("InterfaceModel", theme);
            params.put("uid", user.getUid());
            params.put("userId", user.getUserId());
            params.put("userPriv", user.getUserPriv());
            SessionUtils.putSession(request.getSession(), params, redisSessionCookie);
            SessionUtils.putSession(request.getSession(), user, redisSessionCookie);
            lastOAtargeturl = "";
            response.sendRedirect(targetUrl + OAtargeturl);
        }
        return null;
    }


    /**
     * 创建作者: 刘建
     * 创建日期: 2020-07-14 13:49
     * 方法介绍: 免密登录 跳转相应地址
     * @param request
     * @param response
     * @param OAtargeturl
     * @return void
     */
    @RequestMapping("/loginTwo")
    @ResponseBody
    public void loginTwo(HttpServletRequest request,HttpServletResponse response,String userName ,String OAtargeturl) throws Exception{
        ssoLoginEnter(request, response, null, userName,OAtargeturl);
    }

    /**
     * 创建作者: 刘建
     * 创建日期: 2020-07-14 13:49
     * 方法介绍: 跳转第三方地址
     * @param request
     * @param response
     * @param host
     * @param OAtargeturl
     * @return void
     */
    @RequestMapping("/sendRedirect")
    @ResponseBody
    public void sendRedirect(HttpServletRequest request,HttpServletResponse response ,String host ,String OAtargeturl) throws Exception{
        request.getSession();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        response.sendRedirect(host+"/xoaCas/loginTwo?OAtargeturl="+OAtargeturl+"&userName="+users.getByname());
    }
}

